<template>
  <div class="login">
    <div class="left"></div>
    <div class="loginContainer">
      <h1 class="title">千锋管理系统</h1>
      <i
        @click="iskehuduan = !iskehuduan"
        :class="[
          'iconfont',
          iskehuduan ? 'icon-diannaojiaobiao' : 'icon-erweimajiaobiao',
        ]"
      ></i>
      <div class="fuwuduan" v-if="!iskehuduan">
        <!-- 服务端登录 -->
        <el-form
          :model="loginForm"
          status-icon
          :rules="rules"
          ref="loginForm"
          label-width="100px"
          class="login-loginForm"
        >
          <el-form-item label="用户名" prop="username">
            <el-input
              type="text"
              v-model="loginForm.username"
              autocomplete="off"
            ></el-input>
          </el-form-item>

          <el-form-item label="密码" prop="password">
            <el-input
              type="password"
              v-model="loginForm.password"
              autocomplete="off"
            ></el-input>
          </el-form-item>

          <el-form-item label="验证码" prop="captcha">
            <el-input
              v-model="loginForm.captcha"
              @keydown.enter.native="submitForm('loginForm')"
              ref="captcha"
            ></el-input>
            <div
              class="yzm captcha-svg"
              v-html="captchaSvg"
              @click="updateCaptcha()"
            ></div>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm('loginForm')"
              >提交</el-button
            >
            <!-- <el-button @click="resetForm('loginForm')">重置</el-button> -->
          </el-form-item>
          <!-- 扫码登录 -->
        </el-form>
      </div>
      <div class="erweima" v-else>
        <div>
          <img :src="qrDataUrl" alt="" />

          <i
            class="mask"
            @click="getQrcode"
            :style="qrStyle"
            v-show="isScanCodeSuccess"
          ></i>
        </div>
        <p>请使用微信扫码登录</p>
      </div>
    </div>
    <video
      muted="muted"
      src="../../assets/imgs/bg_video.d2d602a9.mp4"
      autoplay="autoplay"
      loop="loop"
      class="bg_video"
    ></video>
  </div>
</template>
<script>
// 引入api

import * as api from "../../api/index";
import { mapMutations } from "vuex";

//引入socket.io
//引入二维码插件qrcode
import io from "socket.io-client";
import qrcode from "qrcode";

import codeSucessImg from "../../assets/imgs/scancode.png";
import codeInvalidImg from "../../assets/imgs/invalidQr.png";

var validateCaptcha = (rule, value, callback) => {
  if (value.length !== 5) {
    callback("验证码是5位");
  } else {
    callback();
  }
};
var validateUsername = (rule, value, callback) => {
  var reg1 = /^\w{3,12}$/;
  if (reg1.test(value)) {
    callback();
  } else {
    callback("用户名可以是字母数字下划线,3-12位");
  }
};
var validatePassword = (rule, value, callback) => {
  if (value.length < 3) {
    callback("密码必须大于3");
  } else {
    callback();
  }
};

export default {
  data() {
    return {
      qrDataUrl: "", //二维码地址
      isScanCodeSuccess: false, //是否扫码成功
      iskehuduan: false, //是否扫码登陆
      loginForm: {
        username: "",
        password: "",
        captcha: "",
      },
      captchaSvg: "",
      rules: {
        username: [{ validator: validateUsername, trigger: "blur" }],
        password: [{ validator: validatePassword, trigger: "blur" }],
        captcha: [{ validator: validateCaptcha, trigger: "blur" }],
      },
      qrStyle: {
        backgroundImage: `url(${codeSucessImg})`,
      },
    };
  },
  watch: {
    //监听是否切换到二维码登录
    iskehuduan(newVal, oldVal) {
      if (newVal) {
        let socket = io("ws://chst.vip");
        socket.on("connectSuccess", (data) => {
          console.log(data);
          let { sid } = data;
          localStorage.setItem("qf-sid", sid);
          this.getQrcode();
        });

        //用户扫描二维码，监听socket事件，获取wechatCode
        socket.on("scancodeSuccess", (data) => {
          if (data.state) {
            this.isScanCodeSuccess = true;
            api.wechatLoginApi(data.wechatCode).then((res) => {
              if (res.data.state) {
                //登录成功
                // 1token存储到本地
                localStorage.setItem("qf-token", res.data.token);
                // 2userInfo存到本地
                localStorage.setItem(
                  "qf-userInfo",
                  JSON.stringify(res.data.userInfo)
                );
                //3把用户信息，添加到vuex
                this.SET_USER_INFO(res.data.userInfo);
                // 4跳转到页面
                this.$router.push("/");
              } else {
                this.$message.error("微信登入失败");
              }
            });
          } else {
            this.$message.error("微信扫码失败");
          }
        });

        socket.on("invalidCode", (data) => {
          console.log(data);
          this.qrStyle.backgroundImage = `url(${codeInvalidImg})`;
          this.isScanCodeSuccess = true;
          this.qrStyle.cursor = "pointer";
        });
      } else {
        this.isScanCodeSuccess = false;
      }
    },
  },
  mounted() {
    // console.log(process.env.NODE_ENV);
    // console.log(process.env.VUE_APP_BASE_URL);
    this.updateCaptcha(); //调用验证码方法
  },
  methods: {
    // 封装一个方法获取二维码地址的方法
    getQrcode() {
      this.qrStyle.backgroundImage = `url(${codeSucessImg})`;
      let sid = localStorage.getItem("qf-sid");
      if (!sid) {
        this.$message.error("没有sid");
        return;
      }
      api.getQrcodeUrlApi(sid).then((res) => {
        let qrUrl = res.data.scanCodeUrl;
        // 通过qrcode讲url生成二维码
        qrcode.toDataURL(qrUrl, (err, dataUrl) => {
          this.isScanCodeSuccess = false;
          this.qrDataUrl = dataUrl;
        });
      });
    },

    ...mapMutations(["SET_USER_INFO"]),
    //封装一个方法,专门用于获取验证码
    // 获取验证码
    updateCaptcha() {
      api.getCaptchaApi().then((res) => {
        // console.log(res.data);
        this.captchaSvg = res.data.img;
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 表单校验通过，加载动画
          const loading = this.$loading({
            lock: true,
            text: "正在登入",
            spinner: "el-icon-loading iconfont icon-jiazai2zhuanhuan",
            background: "rgba(0, 0, 0, 0.7)",
            duration: "1000*2",
          });
          api
            .verifyCaptcha(this.loginForm.captcha.toLowerCase()) //小写处理
            .then((res) => {
              if (res.data.state) {
                //验证码校验正确，校验用户名和密码
                api
                  .loginApi(this.loginForm.username, this.loginForm.password)
                  .then((res) => {
                    if (res.data.state) {
                      loading.close();
                      //登录成功
                      // 1token存储到本地
                      localStorage.setItem("qf-token", res.data.token);
                      // 2userInfo存到本地
                      localStorage.setItem(
                        "qf-userInfo",
                        JSON.stringify(res.data.userInfo)
                      );
                      //3把用户信息，添加到vuex
                      this.SET_USER_INFO(res.data.userInfo);
                      // 4跳转到页面
                      this.$router.push("/");
                      this.$message({
                        showClose: true,
                        message: "登录成功，正在跳转",
                        type: "success",
                        duration: "1000",
                      });
                      // this.$store.dispatch("GET_MENULIST");调试
                    } else {
                      //登录失败，用户名或者密码错误
                      loading.close();
                      this.$message.error("用户名或者密码错误");
                    }
                  });
              } else {
                //验证码校验错误，刷新验证码
                loading.close();
                this.$message.error("验证码校验错误");
                this.loginForm.captcha = "";
                this.$refs.captcha.foucs();
                this.updataCaptcha();
              }
            });
        } else {
          console.log("error submit");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style lang="less" scoped>
#app {
  .login {
    position: fixed; //解决隐藏滚动条失效
    width: 100%;
    height: 100%;
    .left {
      width: 50%;
      height: 100%;
      background-image: url("../../assets/imgs/bg2.fc58c850.png");
      background-repeat: no-repeat;
      background-size: 50%;
      position: absolute;
      opacity: 0.7;
      background-position: 60% 65%;
    }
    .loginContainer {
      z-index: 9;
      width: 400px;
      height: 487px;
      position: absolute;
      top: 50%;
      left: 75%;
      transform: translate(-50%, -50%);
      border-radius: 11px;
      background: rgba(255, 255, 255, 0.2);
      text-align: center;
      .title {
        text-align: center;
        margin: 0;
        padding: 0;
        list-style: none;
        color: #fff;
        margin-top: 100px;
        margin-bottom: 50px;
      }
      .iconfont {
        font-family: iconfont !important;
        font-style: normal;
        -webkit-font-smoothing: antialiased;
        width: 80px;
        height: 80px;
        overflow: hidden;
        position: absolute;
        right: -1px;
        top: -2px;
        font-size: 50px;
        text-align: right;
        color: #e2e2e2;
        cursor: pointer;
      }
      /deep/.erweima {
        width: 400px;
        height: 273px;
        position: relative;
        > div {
          display: flex;
          justify-content: center;
          margin-bottom: 30px;
          img {
            width: 200px;
            height: 200px;
          }
          .mask {
            background-color: #fff;

            width: 200px;
            height: 200px;
            position: absolute;
            background-size: 50%;
            // top: 0;
            background-repeat: no-repeat;
            background-position: center;

            background: rgba(0, 0, 0, 0.7);
          }
        }
        p {
          color: #fff;
        }
      }
      .login-loginForm {
        text-align: center;
        position: absolute;
        > div {
          /deep/.el-form-item__label {
            color: #fff;
          }
        }
        > div:nth-of-type(1) {
          /deep/.el-form-item__error {
            width: 269px;
            text-align: left;
          }
        }
        > div:nth-of-type(3) {
          /deep/.el-form-item__content {
            display: flex;
            .el-input {
              width: 130px;
              .el-input__inner {
                border-top-right-radius: 0;
                border-bottom-right-radius: 0;
                border-color: #fff;
              }
            }
            .yzm {
              width: 120px;
              height: 40px;
              background: #fff;
              border-radius: 4px;
              border-top-left-radius: 0;
              border-bottom-left-radius: 0;
              border-color: #fff;
              svg {
                width: 120px;
                height: 35px;
              }
            }
          }
        }
        > div:nth-of-type(4) {
          .el-button--primary {
            width: 250px;
            background: linear-gradient(90deg, #1596fb, #002dff);
          }
        }
      }
    }
  }
}
</style>
